/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.dream.modules.system.rest;

import com.dream.annotation.AnonymousAccess;
import com.dream.domain.TaskWork;
import com.dream.modules.system.service.DeptService;
import com.dream.modules.system.service.UserService;
import com.dream.modules.system.service.dto.DeptDto;
import com.dream.modules.system.service.dto.JobSmallDto;
import com.dream.modules.system.service.dto.UserDto;
import com.dream.modules.system.service.mapstruct.UserMapper;
import com.dream.service.TaskWorkService;
import com.dream.service.dto.TaskWorkDto;
import com.dream.service.dto.TaskWorkQueryCriteria;
import com.dream.annotation.Log;
import com.dream.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;

/**
 * @author syl
 * @website https://el-admin.vip
 * @date 2020-07-06
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "工时管理：工时上报")
@RequestMapping("/api/taskWork")

public class TaskWorkController {

    private final TaskWorkService taskWorkService;
    private final UserService userService;
    private final DeptService deptService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('taskWork:list')")
    public void download(HttpServletResponse response, TaskWorkQueryCriteria criteria) throws IOException {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId != 1) {
            UserDto user = userService.findById(currentUserId);
            Set<JobSmallDto> jobs = user.getJobs();
            Iterator<JobSmallDto> iterator = jobs.iterator();
            while (iterator.hasNext()) {
                if ("项目经理".equals(iterator.next().getName())) {
                    criteria.setLeaderId(currentUserId.intValue());
                }
            }
            if (null == criteria.getLeaderId()) {
                criteria.setTaskUserId(currentUserId.intValue());
            }
        }
        List<TaskWorkDto> taskWorkDtos = taskWorkService.queryAll(criteria);
        taskWorkDtos.forEach(t -> {
            DeptDto deptDto = deptService.findById(Long.valueOf(t.getDeptId()));
            UserDto userDto = null;
            if (t.getLeaderId() != null) {
                userDto = userService.findById(t.getLeaderId());
            }
            if (t.getTaskUserId() == null) {
                t.setTaskUserName(userService.findById(t.getTaskUserId()).getUsername());
            }
            if (null != deptDto) {
                t.setDeptName(deptDto.getName());
                if (null != userDto) {
                    t.setLeaderName(userDto.getUsername());
                }
            }
        });
        taskWorkService.download(taskWorkDtos, response);
    }

    @GetMapping
    @Log("查询WorkingController")
    @ApiOperation("查询WorkingController")
    @PreAuthorize("@el.check('taskWork:list')")
    public ResponseEntity<Object> query(TaskWorkQueryCriteria criteria, Pageable pageable) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId != 1) {
            UserDto user = userService.findById(currentUserId);
            Set<JobSmallDto> jobs = user.getJobs();
            Iterator<JobSmallDto> iterator = jobs.iterator();
            while (iterator.hasNext()) {
                if ("项目经理".equals(iterator.next().getName())) {
                    criteria.setLeaderId(currentUserId.intValue());
                }
            }
            if (null == criteria.getLeaderId()) {
                criteria.setTaskUserId(currentUserId.intValue());
            }
        }
        List<TaskWorkDto> list = new ArrayList<TaskWorkDto>();
        Page<TaskWork> taskWorks = taskWorkService.queryPage(criteria, pageable);
        // 转换createBy名称
        taskWorks.forEach(t->{
            if(t.getCreateBy()!=null && CheckUtil.isNum(t.getCreateBy())) {
                UserDto dto = userService.findById(Long.valueOf(t.getCreateBy()));
                t.setCreateBy(dto.getUsername());
            }
        });
        taskWorks.getContent().forEach(t -> {
            DeptDto deptDto = deptService.findById(Long.valueOf(t.getDeptId()));
            UserDto userDto = null;
            if (t.getLeaderId() != null) {
                userDto = userService.findById(t.getLeaderId());
            }
            if (null != deptDto) {
                TaskWorkDto taskWorkDto = this.toDto(t);
                taskWorkDto.setDeptName(deptDto.getName());
                if (null != userDto) {
                    taskWorkDto.setLeaderName(userDto.getUsername());
                }
                list.add(taskWorkDto);
            }
        });
        Page<TaskWork> taskWorks1 = new PageImpl(list, pageable, taskWorks.getTotalElements());
        return new ResponseEntity<>(PageUtil.toPage(taskWorks1), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增WorkingController")
    @ApiOperation("新增WorkingController")
    @PreAuthorize("@el.check('taskWork:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody TaskWork resources) {
        Integer deptId = resources.getDeptId();
        Long currentUserId = SecurityUtils.getCurrentUserId();
        resources.setTaskUserId(currentUserId.intValue());
        resources.setCreateBy(currentUserId+"");
        UserDto userDto = userService.queryLeader(deptId);
        if (!ObjectUtils.isEmpty(userDto)) {
            resources.setLeaderId(userDto.getId().intValue());
        }
        return new ResponseEntity<>(taskWorkService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改WorkingController")
    @ApiOperation("修改WorkingController")
    @PreAuthorize("@el.check('taskWork:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody TaskWork resources) {
        taskWorkService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除WorkingController")
    @ApiOperation("删除WorkingController")
    @PreAuthorize("@el.check('taskWork:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
        taskWorkService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    public TaskWorkDto toDto(TaskWork entity) {
        if (entity == null) {
            return null;
        }

        TaskWorkDto taskWorkDto = new TaskWorkDto();
        taskWorkDto.setId(entity.getId());
        taskWorkDto.setName(entity.getName());
        taskWorkDto.setDeptId(entity.getDeptId());
        taskWorkDto.setLeaderId(entity.getLeaderId());
        taskWorkDto.setStatus(entity.getStatus());
        taskWorkDto.setStartDate(entity.getStartDate());
        taskWorkDto.setActualStartTime(entity.getActualStartTime());
        taskWorkDto.setEndDate(entity.getEndDate());
        taskWorkDto.setStartTime(entity.getStartTime());
        taskWorkDto.setEndTime(entity.getEndTime());
        taskWorkDto.setWorkTime(entity.getWorkTime());
        taskWorkDto.setWorkContent(entity.getWorkContent());
        taskWorkDto.setTaskUserId(entity.getTaskUserId());
        taskWorkDto.setTaskStatus(entity.getTaskStatus());
        taskWorkDto.setCreateTime(entity.getCreateTime());
        taskWorkDto.setCreateBy(entity.getCreateBy());
        taskWorkDto.setUpdateTime(entity.getUpdateTime());
        taskWorkDto.setUpdateBy(entity.getUpdateBy());
        taskWorkDto.setRemark(entity.getRemark());

        return taskWorkDto;
    }


}